package views;


import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import Helper.Log;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.example.administrator.drinkdevice.R;

import org.json.JSONObject;

import Const.PublicDefine;
import Helper.ArcProgress;
import Helper.OnTextCenter;
import Interface.IAsynCallBackListener;

public class Dialog_TakeCup {
    public Context context;
    private Dialog dialog;
    private ArcProgress progressBar;
    private TextView tip;
    private Thread getDeviceStateThread;
    private boolean exitflag = false;
    private String deviceId;
    private int allTime;

    public Dialog_TakeCup(final Context context, JSONObject goodsInfo, int cup) {
        try {
            this.context = context;
            dialog = new Dialog(context);
            dialog.show();
            dialog.setCancelable(false);
            Window window = dialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setContentView(R.layout.dialog_takecup);
            window.setDimAmount(0);
            WindowManager.LayoutParams params = window.getAttributes();
            // 去除四角黑色背景
            window.setBackgroundDrawable(new BitmapDrawable());
            // 设置周围的暗色系数
            params.dimAmount = 0.5f;
            window.setAttributes(params);

            progressBar = dialog.findViewById(R.id.progress);
            tip = dialog.findViewById(R.id.tip);

            tip.setText("请接杯");
            progressBar.setMax(100);
            progressBar.setProgress(0);

            progressBar.setOnCenterDraw(new OnTextCenter());

            if (!goodsInfo.has("pickTime")) {
                throw new Exception("未设置接杯时间");
            }
            JSONObject pickTime = goodsInfo.getJSONObject("pickTime");

            allTime = 0;
            if (cup == 2) {
                if (!pickTime.has("small")) {
                    throw new Exception("未设置接杯时间");
                }
                allTime = pickTime.getInt("small");
            } else {
                if (!pickTime.has("big")) {
                    throw new Exception("未设置接杯时间");
                }
                allTime = pickTime.getInt("big");
            }

            deviceId = goodsInfo.getString("deviceId");
            int res = PublicDefine.colaReader.enter_getCup_setting(deviceId, 1, allTime);
            Log.write("colaReader", "设置接杯时间res: " + res);
            if (res != 0) {
                throw new Exception("设置接杯时间失败");
            }
            res = PublicDefine.colaReader.startGivenSlaveDevice_GetWater(deviceId, 1, 1);
            Log.write("colaReader", "启动接杯res: " + res);
            if (res != 0) {
                throw new Exception("启动接杯失败");
            }

            exitflag = false;
            getDeviceStateThread = new Thread(runnableUi);
            getDeviceStateThread.start();
        } catch (Exception e) {
            e.printStackTrace();
            alert(e.getMessage());
        }
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };

    public void dismiss() {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                dialog.dismiss();
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

    //获取设备状态
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            int round = 30;
            while (!exitflag) {
                try {
                    round--;
                    if (round < 0) {
                        int res = PublicDefine.colaReader.abortGivenSlaveDevice_GetWater(deviceId);
                        Log.write("colaReader", "终止接杯res: " + res);
                        if (res == 0) {
                            alert("已超时, 自动终止接杯");
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        Thread.sleep(3000);//休眠3秒
                                        dismiss();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        alert(e.getMessage());
                                    }
                                }
                            }.start();
                            return;
                        } else {
                            alert("超时自动终止接杯失败[" + res + "]");
                        }
                    }

                    int stateRes = PublicDefine.colaReader.getGivenSlaveDeviceStatus(deviceId);
                    Log.write("colaReader", "获取设备状态res: " + stateRes);
                    if (stateRes == 0) {
                        double takeTime = PublicDefine.colaReader.slave_DeviceInfo.getContained_time() + PublicDefine.colaReader.slave_DeviceInfo.getContained_time_100ms() / 10;
                        setProgress(takeTime);
                        int statusState = PublicDefine.colaReader.slave_DeviceInfo.getStatus_State();
                        Log.write("colaReader", "接杯状态: " + statusState);
                        if (statusState == 0 || statusState == 4) {
                            exitflag = true;
                            setProgress(allTime);
                            alert("接杯完成");
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        Thread.sleep(3000);//休眠3秒
                                        dismiss();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        alert(e.getMessage());
                                    }
                                }
                            }.start();
                            return;
                        } else {
                            if (statusState == 3) {
                                round = 5;
                                alert("接杯中");
                            }
                            if (statusState == 1) {
                                alert("请接杯");
                            }
                            Thread.sleep(1000);
                        }
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    alert(e.getMessage());
                }
            }
        }
    };

    public void alert(final String info) {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                tip.setText(info);
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

    public void setProgress(final double takeTime) {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                double rate = takeTime / allTime;
                int progress = new Double(100 * rate).intValue();
                progressBar.setProgress(progress);
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

}
